import React, { Component, PropTypes } from 'react';
import styles from './ScanGroup.less';
import { message } from 'antd';
import { scanQrCode } from '~/common/sdk/wechat';

class ScanGroup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      securityCode: '',
      buttonText: '切换扫码',
    }
  }
  onScan = (e) => {
    this.setState(({ securityCode, buttonText }) => {
      if (securityCode.length > 0) {
        if (typeof(this.props.callback) === 'function') {
          return this.props.callback.call(this, this.state.securityCode);
        }
        return {
          securityCode: '',
          buttonText: '切换扫码',
        }
      }
      try {
        if (this.props.scanType === 1) {
          return scanQrCode(1)
            .then(this.onScanSecurityCode)
            .catch(err => {
              message.show((err && err.errorMsg) || '扫描防伪码失败！');
            });
        }
        return scanQrCode(2)
          .then(this.onScanProductCode)
          .catch(err => {
            message.show((err && err.errorMsg) || '扫描条形码失败！');
          });
      } catch (ex) {
      } finally {
        return null;
      }
    })
  }
  onScanProductCode = (result) => {
    const code = result.length > 13 ? result.split(',')[1] : result;

    if (!code || code.length > 13) {
      this.setState({
        securityCode: code,
        buttonText: '提交',
      });

      return;
    }

    this.setState({
      securityCode: '',
      buttonText: '切换扫码',
    });
  }
  onScanSecurityCode = (result = '') => {
    const code = result.length > 16 ? result.split('?')[1] : result;
    if (!code || code.length > 16) {
      message.error('您扫的二维码有误，请扫产品瓶盖上的防伪二维码');
      return;
    }

    this.setState({
      securityCode: code,
      buttonText: '提交',
    });
  }
  onChange = (e) => {
    const value = e.target.value;
    this.setState(
      ({
        securityCode,
        buttonText,
      }) => ({
        securityCode: value.length > 16 ? value.substr(0, 16)
          : value,
        buttonText: value.length === 0 ? '切换扫码' : '提交',
      })
    )
  }
  render() {
    return <div className={`${styles.scanGroup} ${this.props.className}`}>
        <button className={styles.scanButton}
          onClick={this.onScan}
        >&nbsp;</button>
        <input className={styles.scanInput}
          type="tel"
          value={this.state.securityCode}
          placeholder={this.props.placeholder}
          onChange={this.onChange}
        />
        <button className={styles.btngreen}
          onClick={this.onScan}
        >{this.state.buttonText}</button>
      </div>
  }
}

ScanGroup.propTypes = {
};

export default ScanGroup;
